package dev.alm.chatmemorydemo.config;

import dev.alm.chatmemorydemo.service.ChatMemoryService;
import dev.alm.chatmemorydemo.service.ChatService;
import dev.alm.chatmemorydemo.service.ChatTokenMemoryService;
import dev.alm.chatmemorydemo.service.StreamService;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.memory.chat.TokenWindowChatMemory;
import dev.langchain4j.model.TokenCountEstimator;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.model.openai.OpenAiStreamingChatModel;
import dev.langchain4j.model.openai.OpenAiTokenCountEstimator;
import dev.langchain4j.service.AiServices;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class LLMConfig {

    @Value("${llm.api.key}")
    private String apiKey;

    @Value("${llm.model.name}")
    private String modelName;

    @Value("${llm.base.url}")
    private String baseUrl;

    @Bean
    public OpenAiChatModel openAiChatModel() {
        return OpenAiChatModel.builder()
                .apiKey(apiKey)
                .modelName(modelName)
                .baseUrl(baseUrl)
                .build();
    }

    @Bean
    public OpenAiStreamingChatModel openAiStreamingChatModel() {
        return OpenAiStreamingChatModel.builder()
                .apiKey(apiKey)
                .modelName(modelName)
                .baseUrl(baseUrl)
                .build();
    }

    @Bean
    public ChatService chatService(OpenAiChatModel openAiChatModel) {
        return AiServices.create(ChatService.class, openAiChatModel);
    }

    @Bean
    public StreamService streamService(OpenAiStreamingChatModel openAiStreamingChatModel) {
        return AiServices.create(StreamService.class, openAiStreamingChatModel);
    }

    @Bean
    public ChatMemoryService chatMemoryService(OpenAiStreamingChatModel openAiStreamingChatModel) {
        return AiServices.builder(ChatMemoryService.class)
                .streamingChatModel(openAiStreamingChatModel)
                .chatMemoryProvider(memoryId -> MessageWindowChatMemory.withMaxMessages(100))
                .build();
    }

    @Bean
    public ChatTokenMemoryService chatTokenMemoryService(OpenAiStreamingChatModel openAiStreamingChatModel) {
        TokenCountEstimator openAiTokenCountEstimator = new OpenAiTokenCountEstimator("gpt-4");
        return AiServices.builder(ChatTokenMemoryService.class)
                .streamingChatModel(openAiStreamingChatModel)
                .chatMemoryProvider(memoryId -> TokenWindowChatMemory.withMaxTokens(1000, openAiTokenCountEstimator))
                .build();
    }


}
